const apiBaseUrl = 'http://47.242.61.211:8000/api/books/';  // 后端 API 地址

let currentBookId = null;
let bookList = [];
let selectedBooks = [];  // 保存选中的图书

window.onload = function () {
    fetchBooks();
}

// 获取图书列表
function fetchBooks() {
    fetch(apiBaseUrl)
        .then(response => response.json())
        .then(data => {
            bookList = data;  // 保存图书列表到全局变量
            updateBookSelect(data);
        })
        .catch(error => console.error('Error fetching books:', error));
}

// 更新下拉框
function updateBookSelect(data) {
    const bookSelect = document.getElementById('bookSelect');
    bookSelect.innerHTML = '<option value="">选择模板</option>';  // 清空下拉菜单
    data.forEach(book => {
        const option = document.createElement('option');
        option.value = book.id;
        option.textContent = book.name;
        bookSelect.appendChild(option);
    });
}

// 搜索图书：根据名称或简介进行搜索
function searchBooks() {
    const searchTerm = document.getElementById('search').value.trim();

    if (searchTerm === "") {
        alert("请输入搜索内容！");
        return;
    }

    // 向后端发送查询请求，搜索名称和简介
    fetch(apiBaseUrl + '?search=' + encodeURIComponent(searchTerm))
        .then(response => response.json())
        .then(data => {
            displaySearchResults(data);  // 展示搜索结果
        })
        .catch(error => console.error('Error searching books:', error));
}

// 显示搜索结果
function displaySearchResults(data) {
    const resultList = document.getElementById('searchResultList');
    resultList.innerHTML = '';  // 清空当前的结果

    data.forEach(book => {
        const li = document.createElement('li');
        li.innerHTML = `
            <input type="checkbox" id="book-${book.id}" onchange="toggleBookSelection(${book.id})">
            <strong>${book.name}</strong><br>
            <em>${book.description}</em><br>
            <button class="copy-btn" onclick="copyToClipboard(${book.id})">复制</button>
        `;
        resultList.appendChild(li);
    });
}

// 切换图书选择状态
function toggleBookSelection(bookId) {
    const checkbox = document.getElementById(`book-${bookId}`);
    if (checkbox.checked) {
        selectedBooks.push(bookId);
    } else {
        selectedBooks = selectedBooks.filter(id => id !== bookId);
    }
}

// 导出选中内容
function exportSelectedBooks() {
    if (selectedBooks.length === 0) {
        alert("请先选择模板！");
        return;
    }

    const selectedBooksData = bookList.filter(book => selectedBooks.includes(book.id));
    
    let txtContent = "选中模板列表:\n\n";
    selectedBooksData.forEach(book => {
        txtContent += `名称: ${book.name}\n简介: ${book.description}\n\n`;
    });

    const blob = new Blob([txtContent], { type: 'text/plain' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = "selected_books.txt";  // 文件名
    link.click();
}
// 复制到剪贴板的函数

function copyToClipboard(bookId) {
    const book = bookList.find(b => b.id === bookId);
    const textToCopy = `模板名称: ${book.name}\n图书简介: ${book.description}`;
//    const book = books.find(b => b.id === bookId);
//    const textToCopy = `${book.name}\n${book.description}`;

    // 创建一个临时文本框
    const textArea = document.createElement('textarea');
    textArea.value = textToCopy;
    document.body.appendChild(textArea);

    // 选择文本并执行复制命令
    textArea.select();
    document.execCommand('copy');

    // 删除临时文本框
    document.body.removeChild(textArea);

    // 提示用户复制成功
    alert('内容已复制到剪贴板！');
}
// 复制图书内容到剪贴板
//function copyToClipboard(bookId) {
//    const book = bookList.find(b => b.id === bookId);
//    const textToCopy = `图书名称: ${book.name}\n图书简介: ${book.description}`;

    // 使用Clipboard API复制文本
//    navigator.clipboard.writeText(textToCopy).then(() => {
//        alert("内容已复制到剪贴板！");
//    }).catch(err => {
//        console.error('复制失败:', err);
//        alert("复制失败，请重试！");
//    });
//}



// 选择图书后加载图书信息
document.getElementById('bookSelect').addEventListener('change', function () {
    const bookId = this.value;

    if (bookId) {
        fetch(apiBaseUrl + bookId)
            .then(response => response.json())
            .then(book => {
                document.getElementById('bookName').value = book.name;
                document.getElementById('bookDesc').value = book.description;
                currentBookId = book.id;
                document.getElementById('bookDescription').textContent = book.description;
            })
            .catch(error => console.error('Error loading book:', error));
    } else {
        clearForm();
    }
});

// 保存或更新图书
function saveBook() {
    const bookName = document.getElementById('bookName').value;
    const bookDesc = document.getElementById('bookDesc').value;

    if (!bookName || !bookDesc) {
        alert("请输入模板名称和简介！");
        return;
    }

    const bookData = {
        name: bookName,
        description: bookDesc
    };

    if (currentBookId) {
        fetch(apiBaseUrl + currentBookId + '/', {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(bookData)
        })
        .then(response => response.json())
        .then(() => {
            fetchBooks();
            clearForm();
            alert("模板信息已更新");
        })
        .catch(error => console.error('Error updating book:', error));
    } else {
        fetch(apiBaseUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(bookData)
        })
        .then(response => response.json())
        .then(() => {
            fetchBooks();
            clearForm();
            alert("新建模板成功");
        })
        .catch(error => console.error('Error saving book:', error));
    }
}
// 删除图书
function deleteBook() {
    if (!currentBookId) {
        alert("请先选择要删除的模板");
        return;
    }

    if (confirm("确认删除该模板？")) {
        fetch(apiBaseUrl + currentBookId + '/', {
            method: 'DELETE'
        })
        .then(() => {
            fetchBooks();
            clearForm();
            alert("模板已删除");
        })
        .catch(error => console.error('Error deleting book:', error));
    }
}

// 清空表单
function clearForm() {
    document.getElementById('bookName').value = '';
    document.getElementById('bookDesc').value = '';
    currentBookId = null;
    document.getElementById('bookDescription').textContent = '';
}
